<?php
namespace app\model;
use app\BaseModel;
use app\console\model\Config;
use app\model\Order as SelfModel;
use think\model\concern\SoftDelete;
use app\model\Member;
use app\model\DistributionType;

class Order extends BaseModel
{

    use SoftDelete;
    protected $deleteTime = 'delete_time';
    protected $defaultSoftDelete = '0000-00-00 00:00:00';
    protected $hidden = ['update_time','delete_time','sort'];
    public $console_status = [ -1=>'已取消',1 => '待付款', 2 => '待发货', 3 => '已发货',4=>'已收货', 5 => '待自提',7 => '已完成',11=>'退款中',12=>'退款成功',13=>'退款失败',14=>'退货中',15=>'退货成功',16=>'退货失败',10=>'已支付(全部)'];
//    public $console_status = [1 => '待付款', 2 => '待发货', 3 => '已发货', 4 => '待自提', 5 => '待配送',6 => '配送中',7 => '已完成'];
    protected $api_status = [1 => '待付款', 2 => '待收货', 3 => '待收货', 4 => '待自提', 5 => '待配送',6 => '配送中',7 => '已完成',8=>'退款中',9=>'退款成功',10=>'退款失败',11=>'退货中',12=>'退货成功',13=>'退货失败'];
    protected $append = ['status_text'];
    /**
     * 搜索器
     * title多字段搜索器
     * like查询可以没有empty
     */
    public function searchStatusAttr($query, $value, $data)
    {

        if (!empty($value)) {
            if ($value == 1 || $value == 2 || $value == 3 || $value == -1) {
                $query->where('status', '=', $value);
            }
            if ($value == 23) {
                $query->where('status', 'in', '2,3');
            }
            if ($value == 7) {
                $query->where('status', 'in', '7');
            }
            if ($value == 4) {
                $query->where('status', 'in', '4'); //必须字符串类型的
            }
            if ($value == 10) {
                $query->where('status', 'between',[2,10]); //必须字符串类型的
            }
            if ($value == 'tui') {
                $where = '(status in (2,3)) or ((status between 7 and 13) and type_id = 2) ';
                $query->where($where);
            }

        }
    }

    public function searchTitleAttr($query, $value, $data)
    {
        if (!empty($value)) {
            $query->where('order_number|name|mobile|company|member_mobile|address', 'like', '%'.$value.'%');
        }
    }
    public function searchGoodsDataAttr($query, $value, $data)
    {
        if (!empty($value)) {
            $query->whereFindInSet('goods_data',$value);
        }
    }
    public function searchIsRefundAttr($query, $value, $data)
    {
        if (!empty($value)) {
            $query->where('is_refund',$value);
        }
    }

    public function searchPayTypeAttr($query, $value, $data)
    {
        if (!empty($value)) {
            $query->where('pay_type',$value);
        }
    }

    public function searchCreateTimeAttr($query,$value,$data){
        if(!empty($value)){
            $start_time = explode(' / ',$value)[0];
            $end_time = date('Y-m-d',strtotime(explode(' / ',$value)[1])+3600*24);
            $query->where('create_time','between',[$start_time,$end_time]);
        }
    }

    protected function getAgoTimeAttr($value,$data)
    {
        return AgoTime($data['create_time']);
    }

    protected function setMultiPicAttr($value, $data)
    {
        if (is_string($value)) $value = implode(',', $value);//把前台的转换成和后台一样的数组;
        $picarr = $value;
        if (!empty($picarr) && is_array($picarr)) {
            $info = input('info/a');
            $show = input('show/a');
            $arr = array();
            foreach ($picarr as $key => $v) {
                $row['img'] = $v;
                if (!empty($info)){
                    $row['info'] = $info[$key];
                }else{
                    $row['info'] = $key+1;
                }
                $row['show'] = $show[$key];
                $arr[] = $row;
            }

            return serialize($arr);
        } else {
            return '';
        }
    }

    protected function getMultiPicAttr($value, $data)
    {
        return unserialize($value);
    }

    protected function getGoodsabcAttr($value, $data)
    {
        $order_goods = (new OrderGoods())->field('order_id,package_id,package_title,package_type,package_total_price')->where('order_number', $data['order_number'])->group('package_id')->select();
        $ga = [];
        foreach ($order_goods as &$v) {
//            $ga = (new OrderGoods())->where('package_id', $v['package_id'])->where('order_id', $v['order_id'])->select();
            $v['goods_list'] = (new OrderGoods())->field('goods_id,title,price,number')->where('package_id', $v['package_id'])->where('order_id', $v['order_id'])->select();
        }
        $str = '';
        echo '<pre/>';
        foreach ($order_goods as $vv){
//            $str .= '套餐名称:'.$vv['package_title'].' 套餐价格:'.$vv['package_total_price']."\r\n";
//            $str .= '';
            foreach ($vv['goods_list'] as $vvv){
                $str .= ' 商品名称:'.$vvv['title'].' 商品价格'.$vvv['price'].' 商品数量:'.$vvv['number']."\r\n";
            }
        }
        return $str;
    }

    public function searchMemberIdAttr($query,$value,$data){

        if(!empty($value)){
            $query->where('member_id','=',$value);
        }

    }

    public function searchDistributionTypeIdAttr($query,$value,$data){
        if(!empty($value)){
            $query->where('distribution_type_id','=',$value);
        }
    }


    protected function setMemberIdAttr($value, $data)
    {   //当前字段的修改器
        $member = Member::where('id', $value)->find();
        $this->set('member_mobile', $member['mobile']);
        $this->set('member_name', $member['name']);
        $this->set('member_nickname', $member['nickname']);
        $this->set('level_id', $member['level_id']);
        return $value;
    }

    protected function setDistributionTypeIdAttr($value, $data)
    { //当前字段的修改器
        $status = [0=>'',2=>'单位自提',1=>'配送到家'];
        $this->set('distribution_type_title', $status[$value]);
        return $value;
    }

    protected function OrderGoods()
    {
        return $this->hasMany('OrderGoods', 'order_id', 'id');
    }

    protected function getStatusTextAttr($value, $data)
    {
        //待付款：修改价格、关闭交易；
        //待发货/待配送：发货、配送分配配送员；
        //待收货/待自提/配送中：查看物流、核销提货、配送状态变化；
        //退款中：处理退款；
        //订单状态  1未支付  2已付款 待发货(待收货) 3已付款 已发货(待收货) 4已付款(待自提) 5已付款(待配送) 6配送中 7已收货 已自提(已完成)

        $module = app('http')->getName();
        if ($module == 'console') {
            $this->console_status;
        } else {
            $this->api_status;
        }
        if(isset($data['status'])){
            return $this->console_status[$data['status']];
        }else{
            return '';
        }

    }

    protected function setExpressCodeAttr($value, $data)
    {
       // dump($data);
        $express_title = Express::where('code',$data['express_code'])->value('title');
        $this->set('express_title',$express_title);
    // $this->set('express_code',$data['express_code']);
        return $value;
    }


    protected function getDistributionTypeAttr($value, $data)
    {
        $status = [ 0 => '-',1 => '快递邮寄', 2 => '门店自提'];
        return $status[$data['distribution_type_id']];
    }

    protected function getRefundTitleAttr($value, $data)
    {
        $status = [ 0 => '-',1 => '否', 2 => '是'];
        if(isset($data['is_refund'])) return $status[$data['is_refund']];
    }

    protected function getPayTitleAttr($value, $data)
    {
        $status = [ 0 => '-',1 => '微信', 2 => '支付',3=>'购物积分'];
        return $status[$data['pay_type']];
    }



    public static function make_borkerage($order_id=1462)
    {

        $order = SelfModel::where('order_number',$order_id)->find();

//        $member = Member::where('id',$member_id)->find();
        $member_id = $order['member_id'];
        $order_number = $order['order_number'];
        $total_price = $order['total_price']; //399 3990 19950
        $number = $order['make_order_count'];
        $level1 = false;//一级是否分润
        $level2 = false;//二级是否分润
        $level3 = false;//二级是否分润
        $red_package = [];
        $red_price = 0;
        $data = parentPath($member_id,'Member');
        $data = array_reverse($data);

        $level_id = $order['level_id']; //系统进入级别
        $level_count = []; //平级数量

//        if($order['level_id'] ==0){
//
////            $default = [
////                1  => ['total'=> 200*$number,1=>100*$number,2=>70*$number,3=>30*$number],
////                2  => ['total'=> 200*$number,1=>100*$number,2=>70*$number,3=>30*$number],
////                3  => ['total'=> 200*$number,1=>100*$number,2=>70*$number,3=>30*$number],
////                4  => ['total'=> 200*$number,1=>100*$number,2=>70*$number,3=>30*$number],
////                5  => ['total'=> 200*$number,1=>100*$number,2=>70*$number,3=>30*$number],
////                6  => ['total'=> 200*$number,1=>100*$number,2=>70*$number,3=>30*$number],
////                7  => ['total'=> 200*$number,1=>100*$number,2=>70*$number,3=>30*$number],
////                8  => ['total'=> 200*$number,1=>100*$number,2=>70*$number,3=>30*$number],
////                9  => ['total'=> 200*$number,1=>100*$number,2=>70*$number,3=>30*$number],
////                10 => ['total'=>2000,1=>1000,2=>700,3=>300],
////                50 => ['total'=>10200,1=>0,2=>1700,3=>8500]
////            ];
//        }else{
//            for ($i=1;$i<=50;$i++){
//                $default[$i] = ['total'=> 100*$number,1=>0,2=>70*$number,3=>30*$number];
//            }
////            $default = [
////                1  => ['total'=> 100*$number,1=>0,2=>70*$number,3=>30*$number],
////                2  => ['total'=> 100*$number,1=>0,2=>70*$number,3=>30*$number],
////                3  => ['total'=> 100*$number,1=>0,2=>70*$number,3=>30*$number],
////                4  => ['total'=> 100*$number,1=>0,2=>70*$number,3=>30*$number],
////                5  => ['total'=> 100*$number,1=>0,2=>70*$number,3=>30*$number],
////                6  => ['total'=> 100*$number,1=>0,2=>70*$number,3=>30*$number],
////                7  => ['total'=> 100*$number,1=>0,2=>70*$number,3=>30*$number],
////                8  => ['total'=> 100*$number,1=>0,2=>70*$number,3=>30*$number],
////                9  => ['total'=> 100*$number,1=>0,2=>70*$number,3=>30*$number],
////                10  => ['total'=> 100*$number,1=>0,2=>70*$number,3=>30*$number],
////                50  => ['total'=> 100*$number,1=>0,2=>70*$number,3=>30*$number],
////            ];
//
//
//        }


        $order_brokerage = 0;

        $member_brokerage = (new MemberBrokerage())->select();
        foreach ($member_brokerage as $vvv){
           // $vvv->delete();
        }
        //复购的时候等级至少1级 所以进不来会员里的逻辑
        if(!empty($data)){
            if($order['level_id'] == 0){
                for ($i=1;$i<=49;$i++){
                    $default[$i] = ['total'=> 200*$number,1=>100*$number,2=>70*$number,3=>30*$number];
                }
                $default[50] =['total'=>10200,1=>0,2=>1700,3=>8500];
                $total_brokerage =$default[$number]['total'];
                foreach ($data as $v){

                    //会员上级大于当前等级
                    if($v['level_id'] > $level_id){    //升级 复购其实级别是1 进不来这个逻辑
//                    if($level_id != 3){  //其他情况平级清0 3级平级不清理
//                        $level_count =0;
//                    }
                        $level_id = $v['level_id']; //设置系统级别

                        if($v['level_id'] == 1 && $number < 10){ //会员 并且小于10的数量的时候触发一级分润
                            $brokerage = $default[$number][$v['level_id']];
                            // $brokerage = $number*100;

                            $total_brokerage -= $brokerage;
//                        echo 'a'.$brokerage;
//                        echo 'aa'.$total_brokerage;;
                            $level1 = true;//分润过
                            $order_brokerage+=$brokerage;
                            MemberBrokerage::saveData($v['id'],$member_id,'会员团队','+',$brokerage,$total_price,$order_number);

                        }
                        if($v['level_id'] == 2){ //进销商
                            $brokerage = 0;
                            if($level1 == false){ //不加number也没问题 因为这个时候1就是0
                                $brokerage += $default[$number][1];//100
//                            echo 'ab'.$brokerage;
//                           // $brokerage = $number*100;
//                            //$total_brokerage -= $brokerage;//会员没有分润,现在就把170纷纭出去 特别注意这里  会员没有分润总佣金也不应该扣掉
//                            echo 'bb2'.$total_brokerage;
                            }
                            $brokerage +=  $default[$number][2];
                            //  $brokerage = $number*70;
                            $total_brokerage -= $brokerage;
                            $order_brokerage+=$brokerage;
//                        echo 'b'.$brokerage;
//                        echo 'bb'.$total_brokerage;;
                            MemberBrokerage::saveData($v['id'],$member_id,'经销商团队','+',$brokerage,$total_price,$order_number);
                        }
                        if($v['level_id'] == 3){ //总代理分润所有 $total_brokerage
                            $red_package[] = $v['id'];
//                            if($level3 == false){ //3级没有分润过
                                $level3 = true;
                                $order_brokerage+=$total_brokerage;
//                            echo 'cc'.$total_brokerage;;
                                MemberBrokerage::saveData($v['id'],$member_id,'总代理团队','+',$total_brokerage,$total_price,$order_number);
                                //$total_brokerage -= 30*$number;
//                            }
                        }
                        continue;
                    }
                    //会员上级大于当前等级
                    //会员上级等于当前等级
                    if($v['level_id'] ==  $level_id && $level_id>=2){ //平级 当前级别和系统级别对比 1 1 2 1
                        $level_count[$level_id][] = 1;
//                    $level_count +=1;
                        // var_dump($level_count);
                        //var_dump($v['id']);
                        $count = count($level_count[$level_id]);
                        if($v['level_id'] == 2 && $count == 1){ //进销商平级一次
                            $brokerage = $number*9;
                            $order_brokerage+=$brokerage;
                            MemberBrokerage::saveData($v['id'],$member_id,'经销商平级','+',$brokerage,$total_price,$order_number);
                        }
                        if($v['level_id'] == 3 && $count ==1){ //总代平级1次

                            $brokerage = $number*9;
                            $order_brokerage+=$brokerage;
                            MemberBrokerage::saveData($v['id'],$member_id,'总代理平级1','+',$brokerage,$total_price,$order_number);
                        }
                        if($level_id == 3 && $count ==2){ //总代平级两次

                            $brokerage = $number*9;
                            $order_brokerage+=$brokerage;
                            MemberBrokerage::saveData($v['id'],$member_id,'总代理平级2','+',$brokerage,$total_price,$order_number);

                        }
                        if($level_id == 3){ //
                            $red_package[] = $v['id'];
                        }
                        continue;
                    }
                    //会员上级等于当前等级
                    //会员上级小于当前等级
                    if($v['level_id'] < $level_id){ //进入小于系统级别 清除平级
//                    if($level_id != 3){  //其他情况平级清0 3级平级不清理
//                        $level_count =0;
//                    }
                        continue;
                    }



                }

            }else{
                //复购
                for ($i=1;$i<=3;$i++){
                    if($order['level_id'] == 1){ //会员复购
                        $default[$i] = ['total'=> 100*$number,1=>0,2=>70*$number,3=>30*$number];
                    }
                    if($order['level_id'] == 2){ //会员复购
                        $default[$i] = ['total'=> 70*$number,1=>0,2=>0,3=>30*$number];
                    }
                    if($order['level_id'] == 3){ //会员复购
                        $default[$i] = ['total'=> 0,1=>0,2=>0,3=>30];
                    }

                }

                $total_brokerage =$default[$order['level_id']]['total'];
                foreach ($data as $v){

                    //会员上级大于当前等级
                    if($v['level_id'] > $level_id){    //升级 复购其实级别是1 进不来这个逻辑
//                    if($level_id != 3){  //其他情况平级清0 3级平级不清理
//                        $level_count =0;
//                    }
                        $level_id = $v['level_id']; //设置系统级别

                        if($v['level_id'] == 2){ //进销商
                            $brokerage = 0;
//                            if($level1 == false){ //不加number也没问题 因为这个时候1就是0
//                                $brokerage += $default[$order['level_id']][2];//100
////                            echo 'ab'.$brokerage;
////                           // $brokerage = $number*100;
////                            //$total_brokerage -= $brokerage;//会员没有分润,现在就把170纷纭出去 特别注意这里  会员没有分润总佣金也不应该扣掉
////                            echo 'bb2'.$total_brokerage;
//                            }
                            $brokerage +=  $default[$order['level_id']][2];
                            //  $brokerage = $number*70;
                            $total_brokerage -= $brokerage;
                            $order_brokerage+=$brokerage;
//                        echo 'b'.$brokerage;
//                        echo 'bb'.$total_brokerage;;
                            $level2 = true;
                            MemberBrokerage::saveData($v['id'],$member_id,'经销商团队','+',$brokerage,$total_price,$order_number);
                        }
                        if($v['level_id'] == 3){ //总代理分润所有 $total_brokerage
                            $red_package[] = $v['id'];
                            $brokerage = 0;
//                            var_dump($total_brokerage);
//                            var_dump($default[$order['level_id']][2]);
                            if($level2 == false){
                                $brokerage +=  $default[$order['level_id']][2];
                            }
                           // var_dump($default[$order['level_id']][3]);
                            $brokerage +=  $default[$order['level_id']][3];
                           // var_dump($total_brokerage);
                                $level3 = true;
                                $order_brokerage+=$brokerage;
//                            echo 'cc'.$total_brokerage;;
                                MemberBrokerage::saveData($v['id'],$member_id,'总代理团队','+',$brokerage,$total_price,$order_number);


                        }
                        continue;
                    }
                    //会员上级大于当前等级
                    //会员上级等于当前等级
                    if($v['level_id'] ==  $level_id && $level_id>=2){ //平级 当前级别和系统级别对比 1 1 2 1
                        $level_count[$level_id][] = 1;
//                    $level_count +=1;
                        // var_dump($level_count);
                        //var_dump($v['id']);
                        $count = count($level_count[$level_id]);
                        if($v['level_id'] == 2 && $count == 1){ //进销商平级一次
                            $brokerage = $number*9;
                            $order_brokerage+=$brokerage;
                            MemberBrokerage::saveData($v['id'],$member_id,'经销商平级','+',$brokerage,$total_price,$order_number);
                        }
                        if($v['level_id'] == 3 && $count ==1){ //总代平级1次
                            $brokerage = $number*9;
                            $order_brokerage+=$brokerage;
                            MemberBrokerage::saveData($v['id'],$member_id,'总代理平级1','+',$brokerage,$total_price,$order_number);
                        }
                        if($level_id == 3 && $count ==2){ //总代平级两次

                            $brokerage = $number*9;
                            $order_brokerage+=$brokerage;
                            MemberBrokerage::saveData($v['id'],$member_id,'总代理平级2','+',$brokerage,$total_price,$order_number);

                        }
                        if($level_id == 3){ //
                            $red_package[] = $v['id'];
                        }
                        continue;
                    }
                    //会员上级等于当前等级
                    //会员上级小于当前等级
                    if($v['level_id'] < $level_id){ //进入小于系统级别 清除平级
//                    if($level_id != 3){  //其他情况平级清0 3级平级不清理
//                        $level_count =0;
//                    }
                        continue;
                    }



                }


            }


            if(!empty($red_package)){
                $c = count($red_package);
                $red_price = $number*9/$c;
                $total_brokerage3 = $number*9;
                foreach ($red_package as $vr){
                    MemberBrokerage::saveData($vr,$member_id,'红包奖励','+',$red_price,$total_price,$order_number);
                }
            }
            $pre = Config::where('varname', 'web_integral')->value('varvalue');
            $integral = $order_brokerage*$pre/100;
            SelfModel::where('order_number',$order_id)->update(['total_brokerage'=>$order_brokerage,'total_brokerage2'=>$integral,'total_brokerage3'=>$total_brokerage3,'total_brokerage4'=>$order['total_price']-$order_brokerage-$integral-$total_brokerage3]);


        }



    }

    /*
     * 支付后根据订单号修改
     * 1修改订单状态
     * 2修改库存
     * 3生成佣金
     * 4修改支付会员等级
     */
    public static function order_update($order_number)
    {

        paylog('========== order_update start ==========');
        paylog($order_number);
        $order = Order::where('order_number', $order_number)->find();
        $level_id = \app\model\Member::where('id', $order['member_id'])->value('level_id');
        paylog($level_id);
        Order::where('order_number', $order_number)->update(['status' => '2', 'pay_time' => date('Y-m-d H:i:s'),'pay_type'=>1]);//修改订单状态
        $order_goods = OrderGoods::where('order_number', $order_number)->select();
        paylog($order_goods);
        foreach ($order_goods as $v) {
            Goods::where('id', $v['goods_id'])->dec('inventory', $v['number'])->update();//修改库存
        }
        Order::make_borkerage($order_number);
        $data = parentPath($order['member_id'],'Member');
        if(!empty($data)){
            foreach ($data as $v){
                (new \app\model\Member())->where('id',$v['id'])->inc('team_price',$order['total_price'])->update();
            }
        }
        //分润完毕 才修改等级
        if ($level_id == 0) {
            if ($order['make_order_count'] < 10) {
                $level_id = 1;
            }
            if ($order['make_order_count'] >= 10 && $order['make_order_count'] < 50) {
                $level_id = 2;
            }
            if ($order['make_order_count'] >= 50) {
                $level_id = 3;
            }
            \app\model\Member::where('id', $order['member_id'])->where('level_id', 0)->update(['level_id' => $level_id]);
        }
        paylog('========== order_update end ==========');
    }






}